import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.net.SocketAddress;

/**
 * Created by xinxingegeya on 16/1/3.
 */
public class Utils {

    private static final String UNIX_DOMAIN_SOCKET_PREFIX = "unix://";

    public static File loadCert(String name) throws IOException {
        InputStream in = Utils.class.getClassLoader().getResourceAsStream(name);
        File tmpFile = File.createTempFile(name, "");
        tmpFile.deleteOnExit();

        BufferedWriter writer = new BufferedWriter(new FileWriter(tmpFile));
        try {
            int b;
            while ((b = in.read()) != -1) {
                writer.write(b);
            }
        } finally {
            writer.close();
        }
        return tmpFile;
    }

    public static SocketAddress parseSocketAddress(String value) {
        if (value.startsWith(UNIX_DOMAIN_SOCKET_PREFIX)) {
            return null;
        } else {
            // Standard TCP/IP address.
            String[] parts = value.split(":", 2);
            if (parts.length < 2) {
                throw new IllegalArgumentException(
                    "Address must be a unix:// path or be in the form host:port. Got: "
                        + value);
            }
            String host = parts[0];
            int port = Integer.parseInt(parts[1]);
            return new InetSocketAddress(host, port);
        }
    }
}
